<template>
    <view class="user-list-component">
        <!-- 搜索栏 -->
        <view class="search-bar">
            <view class="search-input-wrap">
                <input class="search-input" type="text" v-model="searchKeyword" placeholder="请输入行者ID/手机号/昵称"
                    @confirm="handleSearch" />
                <view class="search-icon" @click="handleSearch">
                    <text class="iconfont">🔍</text>
                </view>
            </view>
            <view class="filter-item">
                <picker @change="handleGenderChange" :value="genderIndex" :range="genderOptions" range-key="label">
                    <view class="picker-value">
                        <text>{{ genderOptions[genderIndex].label }}</text>
                    </view>
                </picker>
            </view>
            <view class="filter-item">
                <picker @change="handleStatusChange" :value="statusIndex" :range="statusOptions" range-key="label">
                    <view class="picker-value">
                        <text>{{ statusOptions[statusIndex].label }}</text>
                    </view>
                </picker>
            </view>
        </view>

        <!-- 行者列表 -->
        <view class="user-list">
            <!-- 表头 -->
            <view class="list-header">
                <view class="header-item username">行者ID</view>
                <view class="header-item nickname">昵称</view>
                <view class="header-item phone">手机号</view>
                <view class="header-item gender">性别</view>
                <view class="header-item status">状态</view>
                <view class="header-item register-date">注册时间</view>
                <view class="header-item last-login">最后登录</view>
                <view class="header-item operation">操作</view>
            </view>

            <!-- 加载状态 -->
            <view class="loading-state" v-if="loading">
                <text>数据加载中...</text>
            </view>

            <!-- 空状态 -->
            <view class="empty-state" v-else-if="userList.length === 0">
                <text>暂无行者数据</text>
            </view>

            <!-- 用户数据 -->
            <view class="user-item" v-else v-for="user in userList" :key="user._id">
                <view class="item-cell username">{{ user.userId }}</view>
                <view class="item-cell nickname">{{ user.nickname || '-' }}</view>
                <view class="item-cell phone">{{ formatPhone(user.phone) }}</view>
                <view class="item-cell gender">{{ user.gender === 1 ? '男' : user.gender === 2 ? '女' : '未知' }}</view>
                <view class="item-cell status">
                    <view class="status-tag"
                        :class="{ 'status-enabled': user.status === 1, 'status-disabled': user.status === 0 }">
                        {{ user.status === 1 ? '正常' : '禁用' }}
                    </view>
                </view>
                <view class="item-cell register-date">{{ formatDate(user.register_date) }}</view>
                <view class="item-cell last-login">{{ formatDate(user.last_login_date) }}</view>
                <view class="item-cell operation">
                    <view class="op-btn view" @click="handleViewUserDetails(user)">查看</view>
                    <view class="op-btn" :class="user.status === 1 ? 'disable' : 'enable'"
                        @click="handleToggleStatus(user)">
                        {{ user.status === 1 ? '禁用' : '启用' }}
                    </view>
                </view>
            </view>
        </view>

        <!-- 分页 -->
        <view class="pagination" v-if="total > 0">
            <view class="page-info">
                <text>共 {{ total }} 条记录，当前第 {{ currentPage }}/{{ totalPages }} 页</text>
            </view>
            <view class="page-btns">
                <view class="page-btn" :class="{ disabled: currentPage <= 1 }"
                    @click="handlePageChange(currentPage - 1)">
                    上一页
                </view>
                <view class="page-btn" :class="{ disabled: currentPage >= totalPages }"
                    @click="handlePageChange(currentPage + 1)">
                    下一页
                </view>
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';

// 自定义调用云函数的方法
const callCloudFunction = async (name, data = {}) => {
    try {
        const result = await uniCloud.callFunction({
            name,
            data,
        });
        return result.result;
    } catch (error) {
        console.error(`调用云函数 ${name} 失败:`, error);
        throw error;
    }
};

// 直接调用云函数获取行者列表
const getWalkerList = async (params = {}) => {
    try {
        // 尝试不同的云函数名称
        // 1. 首先尝试使用专用的行者管理云函数
        return await callCloudFunction("getCUserList", params);
    } catch (error) {
        // 如果专用云函数不存在，则尝试使用通用的用户列表云函数
        console.warn('getCUserList云函数调用失败，尝试使用getUserList云函数', error);
        try {
            // 注意：传递type参数，以便在后端区分不同类型的用户
            const userParams = { ...params, type: 'walker' };
            return await callCloudFunction("getUserList", userParams);
        } catch (secondError) {
            console.error('所有云函数调用失败，将使用模拟数据', secondError);
            throw secondError; // 抛出错误，以便外层捕获并使用模拟数据
        }
    }
};

// 搜索条件
const searchKeyword = ref('');
const genderIndex = ref(0);
const statusIndex = ref(0);

// 性别选项
const genderOptions = ref([
    { label: '全部性别', value: '' },
    { label: '男', value: '1' },
    { label: '女', value: '2' },
    { label: '未知', value: '0' }
]);

// 状态选项
const statusOptions = ref([
    { label: '全部状态', value: '' },
    { label: '正常', value: '1' },
    { label: '禁用', value: '0' }
]);

// 用户列表数据
const userList = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);

// 计算总页数
const totalPages = computed(() => {
    return Math.ceil(total.value / pageSize.value) || 1;
});

// 格式化日期
const formatDate = (timestamp) => {
    if (!timestamp) return '-';

    try {
        const date = new Date(timestamp);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hour = String(date.getHours()).padStart(2, '0');
        const minute = String(date.getMinutes()).padStart(2, '0');

        return `${year}-${month}-${day} ${hour}:${minute}`;
    } catch (error) {
        return '-';
    }
};

// 格式化手机号码 (显示中间四位为*)
const formatPhone = (phone) => {
    if (!phone || phone.length !== 11) return phone || '-';
    return phone.substring(0, 3) + '****' + phone.substring(7);
};

// 获取行者列表数据
const fetchUserList = async () => {
    loading.value = true;

    try {
        const params = {
            page: currentPage.value,
            pageSize: pageSize.value,
            keyword: searchKeyword.value,
            gender: genderOptions.value[genderIndex.value].value,
            status: statusOptions.value[statusIndex.value].value
        };

        // 调用云函数获取数据
        const result = await getWalkerList(params);

        if (result.code === 0) {
            userList.value = result.data.list;
            total.value = result.data.total;
        } else {
            uni.showToast({
                title: result.message || '获取行者列表失败',
                icon: 'none'
            });
            userList.value = [];
            total.value = 0;
        }
    } catch (error) {
        console.error('获取行者列表失败', error);
        uni.showToast({
            title: '获取行者列表失败，请检查网络',
            icon: 'none'
        });
        userList.value = [];
        total.value = 0;
    } finally {
        loading.value = false;
    }
};

// 搜索处理
const handleSearch = () => {
    currentPage.value = 1;
    fetchUserList();
};

// 性别筛选变化
const handleGenderChange = (e) => {
    genderIndex.value = e.detail.value;
    handleSearch();
};

// 状态筛选变化
const handleStatusChange = (e) => {
    statusIndex.value = e.detail.value;
    handleSearch();
};

// 分页处理
const handlePageChange = (page) => {
    if (page < 1 || page > totalPages.value) return;
    currentPage.value = page;
    fetchUserList();
};

// 查看用户详情
const handleViewUserDetails = (user) => {
    uni.showToast({
        title: '查看行者详情功能开发中',
        icon: 'none'
    });
};

// 切换用户状态
const handleToggleStatus = (user) => {
    uni.showToast({
        title: '切换行者状态功能开发中',
        icon: 'none'
    });
};

// 页面加载时获取数据
onMounted(() => {
    fetchUserList();
});
</script>

<style>
.user-list-component {
    padding: 20px;
    height: 100%;
    box-sizing: border-box;
    overflow-y: auto;
}

/* 搜索栏样式 */
.search-bar {
    display: flex;
    margin-bottom: 20px;
    background-color: #fff;
    padding: 15px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.search-input-wrap {
    flex: 1;
    display: flex;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
}

.search-input {
    flex: 1;
    height: 40px;
    padding: 0 15px;
    font-size: 14px;
}

.search-icon {
    width: 40px;
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f2f6fc;
    cursor: pointer;
}

.filter-item {
    width: 120px;
    margin-left: 15px;
}

.picker-value {
    height: 40px;
    line-height: 40px;
    padding: 0 10px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    background-color: #f2f6fc;
    font-size: 14px;
    text-align: center;
}

/* 用户列表样式 */
.user-list {
    background-color: #fff;
    border-radius: 4px;
    overflow: hidden;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.list-header {
    display: flex;
    height: 50px;
    background-color: #f2f6fc;
    border-bottom: 1px solid #ebeef5;
}

.header-item {
    padding: 0 10px;
    height: 50px;
    line-height: 50px;
    font-weight: bold;
    color: #606266;
    font-size: 14px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.user-item {
    display: flex;
    border-bottom: 1px solid #ebeef5;
}

.user-item:hover {
    background-color: #f5f7fa;
}

.item-cell {
    padding: 12px 10px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    color: #606266;
    font-size: 14px;
}

/* 各列宽度 */
.username {
    width: 12%;
}

.nickname {
    width: 13%;
}

.phone {
    width: 12%;
}

.gender {
    width: 10%;
}

.status {
    width: 10%;
}

.register-date {
    width: 15%;
}

.last-login {
    width: 15%;
}

.operation {
    width: 13%;
}

/* 状态标签 */
.status-tag {
    display: inline-block;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;
}

.status-enabled {
    background-color: #f0f9eb;
    color: #67c23a;
}

.status-disabled {
    background-color: #fef0f0;
    color: #f56c6c;
}

/* 操作按钮 */
.op-btn {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 4px;
    font-size: 12px;
    margin-right: 10px;
    cursor: pointer;
}

.view {
    background-color: #ecf5ff;
    color: #409eff;
}

.disable {
    background-color: #fef0f0;
    color: #f56c6c;
}

.enable {
    background-color: #f0f9eb;
    color: #67c23a;
}

/* 加载和空状态 */
.loading-state,
.empty-state {
    padding: 40px 0;
    text-align: center;
    color: #909399;
    font-size: 14px;
}

/* 分页 */
.pagination {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
    background-color: #fff;
    padding: 15px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
}

.page-info {
    color: #606266;
    font-size: 14px;
}

.page-btns {
    display: flex;
}

.page-btn {
    padding: 6px 12px;
    margin-left: 10px;
    border-radius: 4px;
    background-color: #ecf5ff;
    color: #409eff;
    font-size: 14px;
    cursor: pointer;
}

.page-btn.disabled {
    background-color: #f4f4f5;
    color: #c0c4cc;
    cursor: not-allowed;
}
</style> 